package com.xtecher.app.user;

import android.content.Context;
import android.text.TextUtils;

import com.xtecher.app.utils.PreferenceUtil;

/**
 * Created by Luhao on 2017/2/24.
 */

public class FollowUtils {
    private static final String KEY = "follow";

    /**
     * 获取本地保存的全部关注
     *
     * @param context
     * @return
     */
    public static String getAllFollow(Context context) {
        return PreferenceUtil.getString(context, KEY);
    }

    /**
     * 添加关注到  sp
     *
     * @param context
     * @param uid
     * @return
     */
    public static boolean addFollow(Context context, String uid) {
        if (TextUtils.isEmpty(uid) || isFollow(context, uid))
            return false;

        String follow = PreferenceUtil.getString(context, KEY);
        StringBuffer stringBuffer = new StringBuffer(follow);
        if (!TextUtils.isEmpty(follow))
            stringBuffer.append(",");
        stringBuffer.append(uid);
        PreferenceUtil.putString(context, KEY, stringBuffer.toString());
        return true;
    }

    /**
     * 取消所有关注
     *
     * @param context
     */
    public static void clearFollow(Context context) {
        PreferenceUtil.putString(context, KEY, "");
    }

    /**
     * 查询是否关注
     *
     * @param c
     * @param uid
     * @return
     */
    public static boolean isFollow(Context c, String uid) {
        if (TextUtils.isEmpty(uid))
            return false;
        String string = PreferenceUtil.getString(c, KEY);
        if (TextUtils.isEmpty(string))
            return false;
        String[] split = string.split(",");
        for (String s : split) {
            if (uid.equals(s))
                return true;
        }
        return false;
    }

    /**
     * 取消单独关注
     *
     * @param c
     * @param uid
     * @return
     */
    public static boolean clearFollow(Context c, String uid) {
        if (TextUtils.isEmpty(uid))
            return false;
        String string = PreferenceUtil.getString(c, KEY);
        if (TextUtils.isEmpty(string))
            return false;
        String[] split = string.split(",");
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            if (!uid.equals(s)) {
                if (!TextUtils.isEmpty(sb.toString()))
                    sb.append(",");
                sb.append(s);
            }
        }
        PreferenceUtil.putString(c, KEY, sb.toString());
        return true;
    }
}
